package com.maosy.demo.webview

import android.annotation.SuppressLint
import android.util.Log
import androidx.fragment.app.Fragment
import com.github.lzyzsd.jsbridge.BridgeWebView
import com.maosy.demo.MyApp
import com.maosy.demo.api.CmsApi
import com.maosy.demo.api.HttpRequest
import com.maosy.demo.api.ServerHost
import com.maosy.demo.util.PermissionUtil
import com.maosy.demo.util.gson
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers

object WebJsBridge {

    fun registerAll(wv: BridgeWebView, fragment: Fragment) {
        test(wv)
        callCmsBanner(wv)
        callLocation(wv, fragment)
    }


    fun test(wv: BridgeWebView) {
        wv.registerHandler(
            "test"
        ) { data, function ->
            Log.i(this::class.simpleName, "data from js:$data")
            function.onCallBack("native get data:$data success.")
        }
    }

    @SuppressLint("CheckResult")
    fun callCmsBanner(wv: BridgeWebView) {
        wv.registerHandler(
            "callCmsBanner"
        ) { data, function ->
            Log.i(this::class.simpleName, "data from js:$data")
            HttpRequest.getApi<CmsApi>(ServerHost.BASE_HOST).banner()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe { function.onCallBack(gson.toJson(it)) }
        }
    }

    fun callLocation(wv: BridgeWebView, fragment: Fragment) {
        wv.registerHandler(
            "callLocation"
        ) { data, func ->
            if (PermissionUtil.checkLocationPerm(
                    fragment.activity ?: throw RuntimeException("activity is error")
                )
            ) {
                func.onCallBack(gson.toJson(MyApp.location))
            }
        }
    }

}